<?php


namespace app\api\controller;

use app\api\BaseApi;
use app\service\PaymentService;
use app\service\UserAccountService;
use app\service\UserService;
use think\response\Json;

/**
 * 支付相关的类
 * Class Payment
 * @package app\api\controller
 */
class Payment extends BaseApi
{
    /**
     * 获取VIP用等级说明
     * @return Json
     */
    public function getVIPInfo(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $day = 365; //vip 有效天数
        $result = [
            'lv1' =>
                [
                    'day' => $day, //vip 有效天数
                    'price' => 1.7, //VIP 收益
                    'fee' => 288, //会员费用
                    'task' => 9, //每日可以领取的任务数量
                    'TotalIncome' => 1377 //预计总收益
                ],
            'lv2' =>
                [
                    'day' => $day, //vip 有效天数
                    'price' => 1.7, //VIP 收益
                    'fee' => 788, //会员费用
                    'task' => 26, //每日可以领取的任务数量
                    'TotalIncome' => 3978 //预计总收益
                ],
            'lv3' =>
                [
                    'day' => $day, //vip 有效天数
                    'price' => 1.7, //VIP 收益
                    'fee' => 1988, //会员费用
                    'task' => 65, //每日可以领取的任务数量
                    'TotalIncome' => 9945 //预计总收益
                ],
            'lv4' =>
                [
                    'day' => $day, //vip 有效天数
                    'price' => 3.2, //VIP 收益
                    'fee' => 3888, //会员费用
                    'task' => 60, //每日可以领取的任务数量
                    'TotalIncome' => 17280 //预计总收益
                ],
            'lv5' =>
                [
                    'day' => $day, //vip 有效天数
                    'price' => 3.2, //VIP 收益
                    'fee' => 5888, //会员费用
                    'task' => 90, //每日可以领取的任务数量
                    'TotalIncome' => 25920 //预计总收益
                ],
            'lv6' =>
                [
                    'day' => $day, //vip 有效天数
                    'price' => 5.6, //VIP 收益
                    'fee' => 8888, //会员费用
                    'task' => 75, //每日可以领取的任务数量
                    'TotalIncome' => 37800 //预计总收益
                ],
            'lv7' =>
                [
                    'day' => $day, //vip 有效天数
                    'price' => 5.6, //VIP 收益
                    'fee' => 12888, //会员费用
                    'task' => 110, //每日可以领取的任务数量
                    'TotalIncome' => 55440 //预计总收益
                ],
        ];
        return $this->success('成功', $result);
    }

    /**
     * 获取支付方式
     * 三种支付方式 银行卡:101,微信:201,支付宝:301,用账号余 401,
     */
    public function getPayMethod(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        //三种支付方式 银行:101,微信:201,支付宝:301
        $payment = [
            'YinHangKa' => 101,
            'WeiXin' => 201,
            'ZhiFuBao' => 301,
            'Balance' => 401, //用账号余额购买VIP
            'ShouXuFeiBiLi' => 0 //支付或者充值的手续费，当前不收，后期收就改这里，比例：0.0001
        ];
        return $this->success('成功', $payment);
    }

    /**
     * 获取平台某个支付渠道某次收款的卡片信息
     * 入参：101
     * 出参：收款信息
     *    例如： 中国工商银行，张三，20099494948483838
     *   微信：201
     *      例如： 收款码
     *   支付宝：301
     *       例如： 收款码
     */
    public function getPayMethodBaseInfo(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //支付类型
        $pay_type = trim(input('pay_type'));
        if (empty($pay_type)) {
            return $this->error('参数错误', '', '100107-04');
        }
        if ($pay_type == '101' || $pay_type == '201' || $pay_type == '301') {
            //检查用户是否在线
            $userService = new UserService();
            $userInfo = $userService->checkUerIsOnlineByToken($user_token);
            if ($userInfo['status'] == 0) {
                return $this->error($userInfo['msg'], '', $userInfo['data']);
            }
            $paymentService = new PaymentService();
            $result = $paymentService->getCardInfoByType($pay_type);
            if ($result['status'] == 0) {
                return $this->error('获取平台收款信息失败--异常', '', '100107-05');
            } else {
                if (empty($result['data'])) {
                    return $this->error('获取平台收款信息失败--没有该收款方式的信息', '', '100107-06');
                } else {
                    if (!empty($result['data']['card_number'])) {
                        $card_number = substr_replace($result['data']['card_number'], '******', 0, 7);
                        $result['data']['card_number'] = $card_number;
                    }
                    if (!empty($result['data']['card_user_name'])) {
                        $card_user_name = substr_replace($result['data']['card_user_name'], '*', 0, 1);
                        $result['data']['card_user_name'] = $card_user_name;
                    }
                    return $this->success('成功', $result['data']);
                }
            }
        } else {
            return $this->error('参数错误', '', '100107-07');
        }
    }

    /**
     * 用户中心--可用余额充值(这个方法可能搞错了)
     */
    public function userChongZhi(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //充值金额，不可小于0也不能超过100000
        $amount = trim(input('amount'));
        if (empty($amount) || $amount <= 0 || $amount > 100000) {
            return $this->error('非法访问', '', '100107-09');
        }
        //用户付款给平台的哪个卡
        $receivable_id = trim(input('receivable_id'));
        if (empty($receivable_id)) {
            return $this->error('平台收款的信息ID不可为空', '', '100107-15');
        }
        //充值成功的图片--支付凭证信息
        $pic = trim(input('pic'));
        if (empty($pic)) {
            return $this->error('非法访问', '', '100107-10');
        }
        //支付类型,银行卡:101,微信:201,支付宝:301
        $pay_type = trim(input('pay_type'));
        if (empty($pay_type)) {
            return $this->error('参数错误', '', '100107-11');
        }
        //业务类型,任务收益类型: 101:充值；201:任务；301:推广；401:团队
        $business_type = trim(input('business_type'));
        if (empty($business_type)) {
            return $this->error('业务类型不可为空', '', '100107-15');
        }
        if ($business_type != 101 && $business_type != 201 && $business_type != 301 && $business_type != 401) {
            return $this->error('业务类型错误', '', '100107-15');
        }
        $vip_lv = 0;
        //如果是充值类型且是开通VIP，则需要传回VIP级别信息
        if ($business_type == 101) {
            //用户VIP级别,1至7级别
            $vip_lv = trim(input('vip_lv'));
            if (!empty($vip_lv) && ($vip_lv < 0 || $vip_lv > 7)) {
                return $this->error('开通VIP级别信息错误', '', '100107-15');
            }
            if (empty($vip_lv)) {
                $vip_lv = 0;
            }
        }
        if ($pay_type == '101' || $pay_type == '201' || $pay_type == '301') {
            //检查用户是否在线
            $userService = new UserService();
            $userInfo = $userService->checkUerIsOnlineByToken($user_token);
            if ($userInfo['status'] == 0) {
                return $this->error($userInfo['msg'], '', $userInfo['data']);
            }
            $user_id = $userInfo['data']['id'];
            $userAccountService = new UserAccountService();
            $result = $userAccountService->userChongZhi($user_id, $amount, $pay_type, $pic_url, $business_type, $vip_lv, $receivable_id);
            if ($result['status'] == 0) {
                return $this->error($result['msg'], '', '100107-13');
            } else {
                return $this->success($result['msg'], $result['data']);
            }
        } else {
            return $this->error('充值类型错误', '', '100107-14');
        }
    }

    /**
     * 用户充值--生成订单（包括开通VIP） 会返回插入成功的ID
     * @return Json
     */
    public function createRechargeOrder(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //充值金额，不可小于0也不能超过100000
        $amount = trim(input('amount'));
        if (empty($amount) || $amount <= 0 || $amount > 100000) {
            return $this->error('非法访问', '', '100107-09');
        }
        $vip_lv = 0;
        //如果是充值类型且是开通VIP，则需要传回VIP级别信息
        //用户VIP级别,1至7级别
        $vip_lv = trim(input('vip_lv'));
        if (!empty($vip_lv) && ($vip_lv < 0 || $vip_lv > 7)) {
            return $this->error('开通VIP级别信息错误', '', '100107-15');
        }
        if (empty($vip_lv)) {
            $vip_lv = 0;
        }
        //return $this->error('非法访问', '', '100107-08');
        //用户付款给平台的哪个卡
        $receivable_id = trim(input('receivable_id'));
        //支付类型,银行卡:101,微信:201,支付宝:301,余额:401
        $pay_type = trim(input('pay_type'));
        if (empty($pay_type)) {
            return $this->error('参数错误', '', '100107-11');
        }
        if ($pay_type != 101 && $pay_type != 201 && $pay_type != 301 && $pay_type != 401) {
            return $this->error('支付类型错误', '', '100107-12');
        } else {
            if($pay_type != 401){
                if (empty($receivable_id)) {
                    return $this->error('平台收款的信息ID不可为空', '', '100107-10');
                }
            }
            //检查用户是否在线
            $userService = new UserService();
            $userInfo = $userService->checkUerIsOnlineByToken($user_token);
            if ($userInfo['status'] == 0) {
                return $this->error($userInfo['msg'], '', $userInfo['data']);
            }
            $user_id = $userInfo['data']['id'];
            $userAccountService = new UserAccountService();
            $result = [];
            //使用余额开通VIP
            if ($pay_type == 401) {
                if($vip_lv == $userInfo['data']['vip_lv']){
                    return $this->error('您已经是LV'.$vip_lv.'级,不用再次升级', '', '100107-17');
                }
                if($vip_lv < $userInfo['data']['vip_lv']){
                    return $this->error('不可以充值降级', '', '100107-18');
                }
                $result = $userAccountService->insertUserAccountCost($user_id, $amount, 2, 0, $vip_lv);
            } else {
                $result = $userAccountService->insertUserAccountRecharge($user_id, $amount, $pay_type, 0, $receivable_id, $vip_lv);
            }
            if ($result['status'] == 0) {
                return $this->error($result['msg'], '', '100107-19');
            } else {
                return $this->success($result['msg'], $result['data']);
            }
        }
    }

    /**
     * 获取支付订单的详情--根据支付单ID
     * @return Json
     */
    public function getRechargeOrderById() : Json {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        $order_id = trim(input('order_id'));
        if (empty($order_id)) {
            return $this->error('参数不可为空', '', '100107-41');
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $user_id = $userInfo['data']['id'];
        $userAccountService = new UserAccountService();
        $result = $userAccountService->getRechargeOrderById($user_id,$order_id);
        if ($result['status'] == 0) {
            return $this->error($result['msg'], '', '100107-43');
        } else {
            //查找平台收款账号信息
            $receivable_id = $result['data']['receivable_id'];
            $r = $userAccountService -> getReceivableByID($receivable_id);
            if($r['status'] == 0){
                return $this->error($r['msg'], '', '100107-44');
            }
            $receivable = [
                'id' => $r['data']['id'],
                'bank_name' => $r['data']['bank_name'],
                'card_user_name' => $r['data']['card_user_name'],
                'card_number' => $r['data']['card_number'],
            ];
            $result['data']['receivable'] = $receivable;
            return $this->success($result['msg'], $result['data']);
        }
    }

    /**
     * 获取用户自己的充值记录--支持动态分页
     * @return Json
     */
    public function getRechargeOrderListByUserId() :Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        $page = trim(input('page'));
        $size = trim(input('size'));
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $user_id = $userInfo['data']['id'];
        $userAccountService = new UserAccountService();
        $result = $userAccountService->getRechargeOrderListByUserId($user_id, $page, $size);
        if ($result['status'] == 0) {
            return $this->error($result['msg']);
        } else {
            return $this->success($result['msg'], $result['data']);
        }
    }

    /**
     * 用户提交支付凭证
     * @return Json
     */
    public function commitRechargeOrder(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        $order_id = trim(input('order_id'));
        if (empty($order_id)) {
            return $this->error('参数不可为空', '', '100107-41');
        }
        $ping_zheng_pic = trim(input('ping_zheng_pic'));
        if (empty($ping_zheng_pic)) {
            return $this->error('参数不可为空', '', '100107-41');
        }
        $remark = trim(input('remark'));
        if (!empty($remark)) {
            if (strlen($remark) > 251) {
                return $this->error('备注太长了', '', '100107-41');
            }
        }

        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $user_id = $userInfo['data']['id'];
        $filename_url = '';
        if(!empty($ping_zheng_pic)){
            $file_path = $_SERVER['DOCUMENT_ROOT'].'/upload/'.date("Ymd").'/'.$user_id;
            $dir = iconv("UTF-8", "GBK",$file_path);
            if (!file_exists($dir)) {
                $r =  mkdir($file_path, 0777, true);
                //创建时间文件夹
                if(!$r){
                    return $this->error('创建文件夹失败','', '100104-18');
                }
            }
            $pics_base = json_decode($ping_zheng_pic,true);
            if(!is_array($pics_base)){
                return $this->error('请传入凭证图片','', '100104-18-04');
            }
            if(count($pics_base) > 3){
                return $this->error('凭证图片最多只用上传3个即可','', '100104-18-03');
            }
            foreach ($pics_base as $key =>$value){
                $arr = preg_split("/(,|;)/",$value);//分隔三部分，data:image/png  base64  后面一堆
                if(count($arr) != 3){
                    return $this->error('Base64图片数据格式严重错误,程序终止执行','', '100104-18-02');
                    die();
                }
                $base64Data = $arr[2];
                $arr2 = explode('/',$arr[0]);      //分割出图片格式
                $file_type = $arr2[1];
                //var_dump($img);

                $img_name = $this -> getFileName();
                $url_p = '/upload/'.date("Ymd").'/'.$user_id.'/'.$img_name.'.'.$file_type;
                if(!empty($filename_url)){
                    $filename_url = $url_p.';'.$filename_url;
                }else{
                    $filename_url = $url_p;
                }

                $filename = $file_path.'/'.$img_name.'.'.$file_type;
                //转码，把utf-8转成gb2312,返回转换后的字符串， 或者在失败时返回 FALSE。
                $filename = iconv("UTF-8","gb2312",$filename);
                //var_dump($filename);die();
                //检查文件是否存在
                if(file_exists($filename)) {
                    return $this->error('已存在同名文件请重新上传','', '100105-18-01');
                }
                $img = base64_decode($base64Data);
                $upload_result = file_put_contents($filename, $img);//返回的是字节数
            }
        }
        //$ping_zheng_pic_url = $filename_url;
        $userAccountService = new UserAccountService();
        $result = $userAccountService->commitRechargeOrder($user_id, $order_id, $filename_url, $remark);
        if ($result['status'] == 0) {
            return $this->error($result['msg'], '', '100107-43');
        } else {
            return $this->success($result['msg'], $result['data']);
        }
    }

    /**
     * 用户取消充值订单
     * @return Json
     */
    public function cancelMyOrderRechargeOrder(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        $order_id = trim(input('order_id'));
        if (empty($order_id)) {
            return $this->error('参数不可为空', '', '100107-51');
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $user_id = $userInfo['data']['id'];
        $remark = trim(input('remark'));
        $userAccountService = new UserAccountService();
        $result = $userAccountService->cancelMyOrderRechargeOrder($user_id, $order_id,$remark);
        if ($result['status'] == 0) {
            return $this->error($result['msg'], '', '100107-53');
        } else {
            return $this->success($result['msg'], $result['data']);
        }
    }

    /**
     * 当用户提现时，获取用户的默认的收款的卡片信息（银行卡，微信，支付宝）
     * 我的收款类型:101 银行卡; 201 微信; 301 支付宝
     */
    public function getUserReceiveDefaultCardInfo(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $userAccountService = new UserAccountService();
        $result = $userAccountService -> getUserReceiveDefaultCardInfo($userInfo['data']['id']);
        if($result['status'] == 0){
            return $this->error($result['msg'], '', '100107-82');
        }else{
            return $this->success($result['msg'], $result['data']);
        }
    }

    /**
     * 用户提现申请
     * @return Json
     */
    public function applyTiXian() : Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //提现金额，不可小于0也不能超过100000
        $amount = trim(input('amount'));
        if (empty($amount) || $amount < 100 || $amount > 100000) {
            return $this->error('提现申请金额错误--提现金额大于100小于10万', '', '100107-91');
        }
        //大于100的整数倍即可
        if(($amount % 100) > 0){
            return $this->error('只能整百提取', '', '100107-91-01');
        }
        //用户提现到自己的哪个卡的ID,用户申请时需要传回
        $card_id = trim(input('card_id'));
        if (empty($card_id)) {
            return $this->error('提现信息ID不可为空', '', '100107-92');
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $user_id = $userInfo['data']['id'];
        $userAccountInfo = $userService->getUserAccountInfoByUserID($user_id);
        if ($userAccountInfo['status'] == 0 || empty($userAccountInfo['data'])) {
            return $this->error($userAccountInfo['msg'], '', '100107-94');
        }
        if ($userAccountInfo['data']['balance'] < 100) {
            return $this->error('可用余额100以下不可提现', '', '100107-95');
        }
        if ($amount > $userAccountInfo['data']['balance']) {
            return $this->error('可用余额不足', '', '100107-96');
        }
        $userAccountService = new UserAccountService();
        $result = $userAccountService->insertUserAccountCost($user_id, $amount, 1, $card_id, 0);
        if ($result['status'] == 0) {
            return $this->error($result['msg'], '', '100107-97');
        } else {
            return $this->success($result['msg'], $result['data']);
        }
    }



}